package com.vancouver.knows.ui.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.ImageView;

import com.pangu.util.StringUtil;
import com.vancouver.knows.R;

/**
 * Created by chenxunlin01 on 2016/5/23.
 */
public class CoverImageView extends ImageView{

    private int coverColor = 0x99ffffff;
    private int coverTextColor = 0xff666666;
    private int coverTextSize = 18;
    private Paint paint = new Paint();
    private Paint coverPaint = new Paint();
    private String text;

    public CoverImageView(Context context) {
        super(context);
    }

    public CoverImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        loadAttributes(attrs,context);
    }

    public CoverImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        loadAttributes(attrs,context);
    }

    private void loadAttributes(AttributeSet attrs, Context context) {
        if (attrs != null && context != null) {
            TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CoverImageView, 0, 0);
            try {
                coverColor = typedArray.getColor(R.styleable.CoverImageView_coverColor, coverColor);
                coverTextColor = typedArray.getColor(R.styleable.CoverImageView_coverTextColor, coverTextColor);
                coverTextSize = typedArray.getDimensionPixelSize(R.styleable.CoverImageView_coverTextSize, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, coverTextSize, context.getResources().getDisplayMetrics()));
            } finally {
                typedArray.recycle();
            }
        }

        paint.setTextAlign(Paint.Align.CENTER);
        paint.setStyle(Paint.Style.STROKE);
        paint.setFlags(Paint.ANTI_ALIAS_FLAG);
        paint.setTypeface(Typeface.SANS_SERIF);
        paint.setColor(coverTextColor);
        paint.setTextSize(coverTextSize);

        coverPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
        coverPaint.setStyle(Paint.Style.FILL);
        coverPaint.setColor(coverColor);
    }

    public void setText(String text) {
        this.text = text;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        canvas.drawRect(0,0,getWidth(),getHeight(),coverPaint);
        if(!StringUtil.isEmptyString(text)){
//            // 计算Baseline绘制的起点X轴坐标 ，计算方式：画布宽度的一半 - 文字宽度的一半
//            int baseX = (int) (canvas.getWidth() / 2 - paint.measureText(text) / 2);
            // 计算Baseline绘制的Y坐标 ，计算方式：画布高度的一半 - 文字总高度的一半
            int baseY = (int) ((canvas.getHeight() / 2) - ((paint.descent() + paint.ascent()) / 2));
            canvas.drawText(text,getWidth()/2,baseY,paint);
        }
    }
}
